<template>
  <div>
    <el-card style="margin: 15px; min-height: calc(100vh - 111px);">
    <el-form :model="queryParams" ref="queryRef" :inline="true" size="small" label-width="68px">
      <el-form-item label="账户名" prop="account">
        <el-input
          v-model="queryParams.account"
          placeholder="请输入账户名"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="身份" prop="roleId">
        <el-select
          v-model="queryParams.roleId"
          placeholder="请选择身份"
          clearable
          @keyup.enter="handleQuery"
        >
          <el-option
            v-for="item in roleList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="请选择账号状态"
          clearable
          @keyup.enter="handleQuery"
        >
          <el-option
            v-for="item in statusList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>
    <el-row
      :gutter="10" class="mb8"
    >
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          >删除</el-button
        >
      </el-col>
    </el-row>
    <el-table
      :data="userList"
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55"> </el-table-column>
      <el-table-column prop="account" label="账户"> </el-table-column>
      <el-table-column prop="roleId" label="身份">
        <template slot-scope="scope">
          {{ scope.row.roleId === 0 ? "管理员" : "普通用户" }}
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态">
        <template slot-scope="scope">
          {{ scope.row.status === 1 ? "正常" : "停用" }}
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" show-overflow-tooltip> </el-table-column>
      <el-table-column prop="updateTime" label="更新时间" show-overflow-tooltip> </el-table-column>
      <el-table-column fixed="right" label="操作">
        <template slot-scope="scope">
          <el-button
            @click="updateStatus(scope.row)"
            type="text"
            size="small"
            :disabled="scope.row.roleId === 0"
          >
            {{ scope.row.status === 1 ? "停用" : "启用" }}
          </el-button>
          <el-button @click="updateInfo(scope.row)" type="text" size="small"
            >编辑</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :page-sizes="[10, 20, 30, 40]"
      :page-size="queryParams.pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="counts"
    >
    </el-pagination>

    <!-- 新增或者修改用户对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="账户" prop="account">
          <el-input v-model="form.account" placeholder="请输入账户名称" />
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="form.id == null">
          <el-input
            v-model="form.password"
            type="password"
            placeholder="请输入密码"
          />
        </el-form-item>
        <el-form-item label="身份" prop="roleId">
          <el-select v-model="form.roleId" placeholder="请选择身份">
            <el-option
              v-for="item in roleList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="创建时间" prop="createTime" v-if="form.id != null">
          {{ form.createTime }}
        </el-form-item>
        <el-form-item label="修改时间" prop="updateTime" v-if="form.id != null">
          {{ form.updateTime }}
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm()">确 定</el-button>
        <el-button @click="open = false">取 消</el-button>
      </div>
    </el-dialog>
    </el-card>
  </div>
</template>

<script>
import {
  page,
  setStatus,
  delUser,
  addUser,
  getUser,
  updateUser,
} from "../api/user";
export default {
  data() {
    return {
      open: false,
      title: "",
      form: {
        id: null,
        account: null,
        password: null,
        roleId: null,
        status: null,
        createTime: null,
        updateTime: null,
      },
      userList: [],
      ids: [],
      multiple: true,
      roleList: [
        { value: 0, label: "管理员" },
        { value: 1, label: "普通用户" },
      ],
      statusList: [
        { value: 0, label: "停用" },
        { value: 1, label: "正常" },
      ],
      counts: 0,
      queryParams: {
        page: 1,
        pageSize: 10,
        account: null,
        roleId: null,
        status: null,
      },
      rules: {
        account: [
          { required: true, message: "请输入账户名称", trigger: "blur" },
          {
            min: 6,
            max: 16,
            message: "长度在 6 到 16 个字符",
            trigger: "blur",
          },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            min: 6,
            max: 16,
            message: "长度在 6 到 16 个字符",
            trigger: "blur",
          },
        ],
        roleId: [{ required: true, message: "请选择身份", trigger: "blur" }],
      },
    };
  },
  mounted() {
    this.getUsers();
  },
  methods: {
    // 重置表单验证状态
    resetFormValidation() {
      this.$nextTick(() => {
        this.$refs.form.clearValidate();
      });
    },
    getUsers() {
      page(this.queryParams)
        .then((response) => {
          if(response.data.code !== 200){
            this.$message({
              message: response.data.msg,
              type: "error",
            });
            return
          }
          this.userList = response.data.data.rows;
          this.counts = response.data.data.total;
        })
        .catch((error) => {
          console.error("Error:", error);
        });
    },
    updateStatus(row) {
      setStatus(row.id)
        .then(this.handleQuery)
        .catch((error) => {
          console.error("Error:", error);
        });
    },
    handleSizeChange(val) {
      this.queryParams.pageSize = val;
      this.getUsers();
    },
    handleCurrentChange(val) {
      this.queryParams.page = val;
      this.getUsers();
    },
    handleQuery() {
      this.queryParams.page = 1;
      this.getUsers();
    },
    resetQuery() {
      this.$refs.queryRef.resetFields();
      this.handleQuery();
    },
    handleSelectionChange(val) {
      this.ids = val.map((item) => item.id);
      this.multiple = !val.length;
    },
    /** 删除按钮操作 */
    handleDelete() {
      const _ids = this.ids;
      delUser(_ids)
        .then((result) => {
          if (result.data.code === 500) {
            this.$message({
              message: result.data.msg,
              type: "warning",
            });
            return;
          }
          this.$message({
            message: "成功删除用户",
            type: "success",
          });
          this.getUsers();
        })
        .catch(() => {});
    },
    reset() {
      this.form = {
        id: null,
        account: null,
        password: null,
        roleId: null,
        status: null,
        createTime: null,
        updateTime: null,
      };
      this.resetFormValidation(); // 重置表单验证状态
    },
    // 新增按钮操作
    handleAdd() {
      this.reset();
      this.title = "新增用户";
      this.open = true;
    },
    // 修改按钮操作
    updateInfo(row) {
      this.reset();
      const _id = row.id;
      getUser(_id).then((result) => {
        this.form = result.data.data;
        this.title = "修改用户";
        this.open = true;
        console.log(this.form);
      });
    },
    //  提交按钮操作
    submitForm() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateUser(this.form).then((result) => {
              if (result.data.code === 500) {
                this.$message({
                  message: result.data.msg,
                  type: "warning",
                });
              } else {
                this.$message({
                  message: "修改用户成功",
                  type: "success",
                });
                this.getUsers();
                this.open = false;
              }
            });
          } else {
            addUser(this.form).then((result) => {
              if (result.data.code === 500) {
                this.$message({
                  message: result.data.msg,
                  type: "warning",
                });
              } else {
                this.$message({
                  message: "添加用户成功",
                  type: "success",
                });
                this.getUsers();
                this.open = false;
              }
            });
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
  },
};
</script>
  
<style>
</style>